<template>
  <div>
    <el-card class="box-card">
      <el-tabs value="activeName">
        <el-tab-pane label="组织架构" name="activeName">
          <div class="box">
            <ul class="custom-tree">
              <li class="title">
                <i class="el-icon-s-home"></i>
                <span>江苏传智播客教育科技股份有限公司</span>
              </li>
              <li>
                <ul class="custom-tree">
                  <li>负责人</li>
                  <li>
                    <el-dropdown>
                      <span class="el-dropdown-link">
                        操作<i class="el-icon-arrow-down el-icon--right"></i>
                      </span>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item @click.native="createDialog()"
                          >添加子部门</el-dropdown-item
                        >
                      </el-dropdown-menu>
                    </el-dropdown>
                  </li>
                </ul>
              </li>
            </ul>
            <!-- 分界线 -->
            <el-divider></el-divider>
            <!-- 树形控件 -->
            <el-tree
              :data="branchlist"
              :props="defaultProps"
              default-expand-all
            >
              <ul
                slot-scope="{ node, data }"
                class="custom-tree-node custom-tree"
              >
                <li>
                  <i class="el-icon-folder-add"></i>
                  {{ node.label }}
                </li>
                <li>
                  <ul class="custom-tree">
                    <li>
                      {{ data.responsible ? data.responsible.user : "无" }}
                    </li>
                    <li>
                      <el-dropdown>
                        <span class="el-dropdown-link">
                          操作<i class="el-icon-arrow-down el-icon--right"></i>
                        </span>
                        <el-dropdown-menu slot="dropdown">
                          <el-dropdown-item @click.native="createDialog(data)">
                            添加子部门
                          </el-dropdown-item>
                          <el-dropdown-item @click.native="editDialog(data)">
                            查看部门
                          </el-dropdown-item>
                          <el-dropdown-item @click.native="delbreach(data)">
                            删除部门
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </el-dropdown>
                    </li>
                  </ul>
                </li>
              </ul>
            </el-tree>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!--   添加和编辑的对话框 -->
    <el-dialog
      :title="dialogData.title"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <el-form
        ref="form"
        :model="branch"
        label-width="100px"
        :rules="branchRules"
      >
        <el-form-item label="部门名称" prop="b_name">
          <el-input
            v-model="branch.b_name"
            :disabled="ischeckbranch"
          ></el-input>
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="branch.code" :disabled="ischeckbranch"></el-input>
        </el-form-item>
        <el-form-item label="部门负责人" prop="responsible">
          <el-select
            v-model="branch.responsible"
            placeholder="请选择部门负责人"
            :disabled="ischeckbranch"
          >
            <el-option
              v-for="item in userlist"
              :key="item._id"
              :label="item.user"
              :value="item._id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduction">
          <el-input
            v-model="branch.introduction"
            :disabled="ischeckbranch"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm">取 消</el-button>
        <el-button type="primary" @click="dialogData.fn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { branchs, createBranch, editbranch, delbranch } from "@/axios/brank";
import { users } from "@/axios/user";
import { mapState } from "vuex";
export default {
  name: "Vue",
  props: {},
  data() {
    return {
      ischeckbranch: false,
      dialogVisible: false,
      branchlist: [],
      defaultProps: {
        children: "children",
        label: "b_name",
      },
      branch: {
        b_name: undefined,
        code: undefined,
        introduction: undefined,
        code: undefined,
        b_id: undefined,
        responsible: undefined,
      },
      dialogData: {
        title: "",
        fn: "",
      },
      userlist: [],
      branchRules: {},
      // 下级部门存放
      branchId: [],
      breachs: [],
    };
  },
  created() {
    this.getdata();
    this.getuser();
  },
  methods: {
    // 获取所有的用户
    async getuser() {
      let { data } = await users();
      if (data.code != 200) {
        this.$message.error(data.code);
        return;
      }
      this.userlist = data.data;
      // if (this.user.responsible == 1) {
      //   if (["管理员", "超级管理员"].indexOf(this.user.user) == -1) {
      //     let breachid = [];
      //     if (this.user.responsible) {
      //       this.user.b_id.forEach((item) => {
      //         breachid.push(item._id);
      //       });
      //     }
      //     this.userlist = this.userlist.filter((item) => {
      //       if (Array.isArray(item.b_id)) {
      //         for (let i in item.b_id) {
      //           if (
      //             breachid.includes(item.b_id[i]._id) |
      //             breachid.includes(item.b_id[i].b_id) |
      //             ["管理员", "超级管理员"].includes(item.user)
      //           ) {
      //             return item;
      //           }
      //         }
      //       } else {
      //         return breachid.includes(item.b_id._id);
      //       }
      //     });
      //   }
      // }
    },
    // 对部门数据进行解析
    getchildren(datalist, data) {
      datalist.forEach((item) => {
        item.children = data.filter((item1) => {
          return item._id == item1.b_id._id;
        });
        item.children =
          this.getchildren(item.children, data) == []
            ? this.getchildren(item.children, data)
            : item.children;
      });
      return datalist;
    },
    // 获取部门数据
    async getdata() {
      let { data } = await branchs();
      if (data.code != 200) {
        this.$message.error(data.msg);
        return;
      }
      this.breachs = data.data;
      // 获取到一级部门
      let datalist = data.data.filter((item) => {
        return !item.b_id;
      });
      // 获取到非一级部门
      let dataA = data.data.filter((item) => {
        return item.b_id;
      });
      this.branchlist = this.getchildren(datalist, dataA);
      this.branchId = this.getBreachId(this.branchlist);
    },
    // 获取下级部门id
    getBranchIdList(data) {
      let a = [];
      data.forEach((item) => {
        a.push(item._id);
        if (item.children) {
          a.push(...this.getBranchIdList(item.children));
        }
      });
      return a;
    },
    // 获取当前用户负责的部门的下级部门的部门id
    getBreachId(data) {
      let datalist = [];
      data.forEach((item) => {
        if (item.responsible) {
          if (item.responsible._id == this.user._id) {
            // 当前用户为部门负责人
            datalist.push(...this.getBranchIdList(item.children));
          } else if (item.children.length > 0) {
            // 当前部门有下级部门
            this.getBreachId(item.children);
          }
        }
      });
      return datalist;
    },
    // 添加部门打开对话框
    createDialog(data) {
      if (!data & (["管理员", "超级管理员"].indexOf(this.user.user) == -1)) {
        this.$message.info("您暂无该权限！！！");
        return;
      }
      if (
        (data.responsible._id != this.user._id) |
        (["管理员", "超级管理员"].indexOf(this.user.user) != -1)
      ) {
        this.$message.info("您暂无该权限！！！");
        return;
      }
      this.ischeckbranch = false;
      this.branch.b_id = data._id;
      this.dialogData.title = "添加部门";
      this.dialogData.fn = this.upbranch;
      this.dialogVisible = true;
    },
    // 添加数据
    async upbranch() {
      let { data } = await createBranch(this.branch);
      if (data.code != 200) {
        this.$message.error(data.msg);
      }
      this.resetForm();
      this.getdata();
    },
    // 重置表单
    resetForm() {
      this.$refs.form.resetFields();
      this.dialogVisible = false;
    },
    // 删除部门
    async delbreach(dataa) {
      if (
        (this.branchId.indexOf(dataa._id) == -1) &
        (["管理员", "超级管理员"].indexOf(this.user.user) == -1)
      ) {
        this.$message.info("您暂无该权限！");
      }
      if (("总裁办" == dataa.b_name) & (this.user.users != "超级管理员")) {
        this.$message.info("您暂无该权限！");
      }
      let { data } = await delbranch(dataa._);
      if (data.code != 200) {
        this.$message.error(data.msg);
        return;
      }
      this.getdata();
    },
    // 修改的弹出框
    editDialog(data) {
      if (
        (this.branchId.indexOf(data._id) != -1) |
        (["管理员", "超级管理员"].indexOf(this.user.user) != -1)
      ) {
        this.ischeckbranch = false;
      } else {
        this.ischeckbranch = true;
      }
      this.$nextTick(() => {
        this.branch = JSON.parse(JSON.stringify(data));
        // console.log(this.branch);
        this.branch.responsible = this.branch.responsible._id;
      });
      this.dialogData.title = "查看部门";
      this.dialogData.fn = this.editbranch;
      this.dialogVisible = true;
    },
    async editbranch() {
      let { data } = await editbranch(this.branch._id, this.branch);
      if (data.code != 200) {
        this.$message.error(data.msg);
      }
      this.getdata();
      this.resetForm();
    },
  },
  watch: {
    dialogVisible() {
      if (!this.dialogVisible) {
        this.resetForm();
      }
    },
  },
  computed: {
    ...mapState(["user"]),
  },
};
</script>

<style lang="scss" scoped>
.custom-tree {
  list-style: none;
  padding: 0;
  list-style: none;
  padding: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.box {
  padding: 30px 130px 0;
}
i {
  margin-right: 10px;
}
.el-dropdown {
  margin-left: 40px;
}
.title {
  color: black;
  font-weight: 800;
}
::v-deep(.el-dialog__header) {
  background-color: rgb(29, 116, 116) !important;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
